package com.android.Lmaps;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.json.JSONObject;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

///request code: ActivityAddphongtro - 111
///request code: MarkerEventMenu - 112
///request code: show list - 113
public class MainActivity extends FragmentActivity {
	public PolylineOptions polyline;
	ProgressDialog progressD;
	
	DBphongtro databasePhongtro =null;
	ArrayList<phongtro>listLocation = null;
	ArrayList<phongtro>listNull = null;

	AdapterPT adtPT = null;
	GetLocations myLocationAddress;
	LatLng locationOrigin = null;
	LatLng locationDest = null;
	
	///-------------------------------------end array
	GoogleMap mymap;
	Button btnAdd,btnmapstype;
	ListView lsvShow;
	EditText txtSearch;
	///-------------------------------------end view
	int flagAdd = 0;//cancel
	//1 add
	//2 select all   // remove select
	//3 clear select // remove select
	///-------------------------------------end flag
	String data = "";
	Boolean flagChoice=false;
	
	@Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("start", "0");
        setContentView(R.layout.activity_main);
        Log.d("start", "1");
        btnAdd=(Button)findViewById(R.id.button_main_add);
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map);
        mymap = fm.getMap();
        //mymap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
        btnmapstype=(Button)findViewById(R.id.button_main_mapstype);
        lsvShow=(ListView)findViewById(R.id.listView_main_showlist);
        txtSearch =(EditText)findViewById(R.id.editText_main_search);

        databasePhongtro = new DBphongtro(this);
        listLocation = new ArrayList<phongtro>();
        listLocation = databasePhongtro.findAll();
        
        listNull = new ArrayList<phongtro>();
        
        adtPT = new AdapterPT(this, R.layout.activity_adapter_pt, listNull);
        
       lsvShow.setAdapter(adtPT);
        Log.d("start", "2");
        //----------------------------------------------------
        Log.d("start", "5");
        mymap.setMyLocationEnabled(true);
        Log.d("start", "6");
        ///set map stype
        //mymap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        Log.d("start", "7");
        
        //get my location
        myLocationAddress = new GetLocations(getApplicationContext());
        //create point LatLng (latitude and longitude)
        locationOrigin = new LatLng(myLocationAddress.getLatitude(), myLocationAddress.getLongitude());
        //setting type of maps and show my location
        mymap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(locationOrigin, 16);
        mymap.animateCamera(update);
        

        
        refeshEdit();

        
        Log.d("start", "8");
        //-----------------------------------------------------------------------------------------------
        txtSearch.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				//  
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(s.length()==0)
				{
					//setting to show map
					
					flagAdd = 0;
					flagChoice=false;
					btnAdd.setText("add");
					btnAdd.setBackgroundColor(Color.GREEN);
					lsvShow.clearTextFilter();
					if(mymap.getMapType()==GoogleMap.MAP_TYPE_NORMAL)
					{
						btnmapstype.setBackgroundResource(R.drawable.maps);
					}
					else
					{
						btnmapstype.setBackgroundResource(R.drawable.startmaps);
					}
				}
				else
				{
					if(flagAdd <2)
					{
						//setting for list show
						adtPT.addAll(listLocation);
						btnAdd.setText("all");
						btnAdd.setBackgroundColor(Color.GREEN);
						flagAdd =2;
						btnmapstype.setBackgroundResource(R.drawable.clear_storage);
					}
					else
					{
						adtPT.getFilter().filter(s, lsvShow);
					}
				}
			}
		});
        
        //-----------------------------------------------------------------------------------------------
        btnAdd.setBackgroundColor(Color.GREEN);
        btnAdd.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (flagAdd) {
				case 0:
					btnAdd.setText("cacel");
					btnAdd.setBackgroundColor(Color.RED);
					flagAdd=1;
					break;
				case 1:
					btnAdd.setText("add");
					btnAdd.setBackgroundColor(Color.GREEN);
					flagAdd=0;
					break;
				case 2:
					btnAdd.setText("clear");
					btnAdd.setBackgroundColor(Color.GREEN);
					//function select all
					for (int i = 0; i < adtPT.getCount(); i++) {
						View pt = lsvShow.getChildAt(i);
						CheckBox chk = (CheckBox)pt.findViewById(R.id.checkBox_adt_check);
						chk.setChecked(true);
						ImageView img = (ImageView)pt.findViewById(R.id.imageView_adt_icon);
						img.setBackgroundResource(R.drawable.checkbox_true);
					}
					flagChoice=true;
					flagAdd=3;
					break;
				case 3:
					btnAdd.setText("all");
					btnAdd.setBackgroundColor(Color.GREEN);
					// function clear select
					for (int i = 0; i < adtPT.getCount(); i++) {
						View pt = lsvShow.getChildAt(i);
						CheckBox chk = (CheckBox)pt.findViewById(R.id.checkBox_adt_check);
						chk.setChecked(false);
						ImageView img = (ImageView)pt.findViewById(R.id.imageView_adt_icon);
						img.setBackgroundResource(R.drawable.checkbox_unchecked);
					}
					flagAdd=2;
					break;
				default:
					break;
				}
			}
		});
      //-----------------------------------------------------------------------------------------------
        lsvShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if(flagChoice)
				{
					View pt = lsvShow.getChildAt(arg2);
					CheckBox chk = (CheckBox)pt.findViewById(R.id.checkBox_adt_check);
					if(chk.isChecked())
					{
						chk.setChecked(false);
					}
					else
					{
						chk.setChecked(true);
					}
				}
				else
				{
					phongtro showpt = listLocation.get(arg2);
					LatLng comeHere = new LatLng(showpt.getLat(), showpt.getLon());
			        //setting type of maps and show my location
			        mymap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(comeHere, 16);
			        //
			        flagAdd = 0;
					btnAdd.setText("add");
					btnAdd.setBackgroundColor(Color.GREEN);
					adtPT.clear();
					if(mymap.getMapType()==GoogleMap.MAP_TYPE_NORMAL)
					{
						btnmapstype.setBackgroundResource(R.drawable.maps);
					}
					else
					{
						btnmapstype.setBackgroundResource(R.drawable.startmaps);
					}
			        //
			        mymap.animateCamera(update);
				}
				
			}
		});
        lsvShow.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				flagChoice = true;
				View pt = lsvShow.getChildAt(arg2);
				CheckBox chk = (CheckBox)pt.findViewById(R.id.checkBox_adt_check);
				chk.setChecked(true);
				ImageView img = (ImageView)pt.findViewById(R.id.imageView_adt_icon);
				img.setBackgroundResource(R.drawable.checkbox_true);
				return false;
			}
		});
        
        
        
        btnmapstype.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(flagAdd<2)
				{
					if(mymap.getMapType()==GoogleMap.MAP_TYPE_NORMAL)
					{
						mymap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
						btnmapstype.setBackgroundResource(R.drawable.startmaps);
					}
					else
					{
						mymap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
						btnmapstype.setBackgroundResource(R.drawable.maps);
					}
			}
				else
				{
					for (int i = adtPT.getCount()-1; i >=0 ; i--) {
						View pt = lsvShow.getChildAt(i);
						CheckBox chk = (CheckBox)pt.findViewById(R.id.checkBox_adt_check);
						if(!chk.isChecked())
						{
							if(databasePhongtro.removephongtro(adtPT.getItem(i).getId()))
							{
								adtPT.remove(adtPT.getItem(i));
								listLocation.remove(i);
							}
							
						}
					}
					refeshEdit();
				}
			}
		});
  
      //-----------------------------------------------------------------------------------------------
       
        //-----------------------------------------------------------------------------------------------
      //event click on the map, if you was enable add, so you can touch on to any location and add new one
        mymap.setOnMapClickListener(new OnMapClickListener() {
			
			@Override
			public void onMapClick(LatLng point) {
				// TODO Auto-generated method stub
				
				//onCreateOptionsMenu();
				if(flagAdd<2)
				{
					//get the location when i click on the map
					
					if(flagAdd==1)
					{
						// create new location
						Intent addLocation = new Intent(MainActivity.this, AddNewLocation.class);
						Bundle mydata = new Bundle();
						mydata.putDouble("lat", point.latitude);
						mydata.putDouble("lon", point.longitude);
						mydata.putBoolean("stype", true);
						addLocation.putExtras(mydata);
						btnAdd.setText("add");
						btnAdd.setBackgroundColor(Color.GREEN);
						flagAdd=0;
						startActivityForResult(addLocation, 111);
					}
				}
				else
				{
					flagAdd=0;
					btnAdd.setText("add");
					btnAdd.setBackgroundColor(Color.GREEN);
					adtPT.clear();
					if(mymap.getMapType()==GoogleMap.MAP_TYPE_NORMAL)
					{
						btnmapstype.setBackgroundResource(R.drawable.maps);
					}
					else
					{
						btnmapstype.setBackgroundResource(R.drawable.startmaps);
					}
					txtSearch.clearFocus();
				}
			}
		});
        
        //set event click on the marker
        mymap.setOnMarkerClickListener(new OnMarkerClickListener() {
			
			@Override
			public boolean onMarkerClick(Marker marker) {
				// TODO Auto-generated method stub
				if(flagAdd<2)
				{
					//show menu action
					for (phongtro ptx : listLocation) {
						if(ptx.getLat().equals(marker.getPosition().latitude))
						{
							if(ptx.getLon().equals(marker.getPosition().longitude))
							{
								Intent intMenu = new Intent(MainActivity.this, MarkerClick.class);
								Bundle mydata = new Bundle();
								mydata.putString("id", ptx.getId());
								mydata.putString("address", ptx.getAddress());
								mydata.putDouble("lat", ptx.getLat());
								mydata.putDouble("lon", ptx.getLon());
								mydata.putDouble("price", ptx.getPrice());
								mydata.putString("description", ptx.getDescription());
								mydata.putString("contact", ptx.getContact());
								mydata.putBoolean("personshare", ptx.getPersonShare());
								
								intMenu.putExtras(mydata);
								startActivityForResult(intMenu, 112);
							}
						}
					}
				}
				else
				{
					flagAdd=0;
					btnAdd.setText("add");
					btnAdd.setBackgroundColor(Color.GREEN);
					adtPT.clear();
					if(mymap.getMapType()==GoogleMap.MAP_TYPE_NORMAL)
					{
						btnmapstype.setBackgroundResource(R.drawable.maps);
					}
					else
					{
						btnmapstype.setBackgroundResource(R.drawable.startmaps);
					}
					txtSearch.clearFocus();
				}
				return false;
			}
		});
        
        
      //-----------------------------------------------------------------------------------------------
      //-----------------------------------------------------------------------------------------------
     }
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		switch (id) {
		case 0:
			progressD = new ProgressDialog(this);
			progressD.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressD.setMessage("Loading.....");
			
			return progressD;
		}

		return super.onCreateDialog(id, args);
	}
	//-----------------------------------------------------------------------------------------------
       

    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 111:// add new point
			Log.d("add new", "5");
			if(resultCode==Activity.RESULT_OK)
			{
				Log.d("add new", "6");
				Bundle myBundle = data.getExtras();
				String _address = myBundle.getString("address");
				String _description = myBundle.getString("description");
				String _contact = myBundle.getString("contact");
				Double _price = myBundle.getDouble("price");
				Boolean _personshare = myBundle.getBoolean("personshare");
				Double _latitude = myBundle.getDouble("lat");
				Double _longitude=myBundle.getDouble("lon");
				Log.d("add new", "7");
				phongtro _pt = new phongtro();
				Log.d("add new", "8");
				_pt.setAddress(_address);
				_pt.setContact(_contact);
				_pt.setDescription(_description);
				_pt.setPrice(_price);
				_pt.setPersonShare(_personshare);
				_pt.setLat(_latitude);
				_pt.setLon(_longitude);
				_pt.setTime();
				_pt.setId();
				Log.d("add new", "9");
				if(databasePhongtro.createphongtro(_pt))
				{
					Log.d("add new", "10a");
					listLocation.add(_pt);
					Toast.makeText(getApplicationContext(), "add is success", Toast.LENGTH_LONG).show();
					Log.d("add new", "11a");
				}
				else
				{
					Log.d("add new", "10b");
					Toast.makeText(getApplicationContext(), "add is not success", Toast.LENGTH_LONG).show();
					Log.d("add new", "11b");
				}
				Log.d("add new", "12");
			}
			break;
		case 112:// select action on marker
			if(resultCode==Activity.RESULT_OK)
			{
				Bundle myBundle = data.getExtras();
				int mytype = myBundle.getInt("type");
				String _address = myBundle.getString("address");
				String _description = myBundle.getString("description");
				String _contact = myBundle.getString("contact");
				Double _price = myBundle.getDouble("price");
				Boolean _personshare = myBundle.getBoolean("personshare");
				String _id = myBundle.getString("id");
				Double _latitude = myBundle.getDouble("lat");
				Double _longitude=myBundle.getDouble("lon");
				switch (mytype) {
				case 0://get the way PolylineOptions  locationOrigin
					if(!isOnline())
					{
						Toast.makeText(getApplicationContext(), "Sorry! Network is not wolking", Toast.LENGTH_LONG).show();
						return;
					}
					locationDest = new LatLng(_latitude, _longitude);
					showDialog(0);
					DownloadTask mytask =new DownloadTask();
					mytask.execute();
					
					break;
				case 1://remove this location
					if(databasePhongtro.removephongtro(_id))
					{
						for(int i = 0;i<=listLocation.size();i++)
						{
							phongtro ptx = listLocation.get(i);
							if(ptx.getId().equals(_id))
							{
								listLocation.remove(i);
								Toast.makeText(getApplicationContext(), "Remove is success", Toast.LENGTH_LONG).show();
								break;
							}
						}
					}
					else
					{
						Toast.makeText(getApplicationContext(), "Remove is not success", Toast.LENGTH_LONG).show();
					}
					break;
				case 2://edit this location
					phongtro _pt = new phongtro();
					_pt.setId(_id);
					_pt.setAddress(_address);
					_pt.setDescription(_description);
					_pt.setContact(_contact);
					_pt.setPrice(_price);
					_pt.setPersonShare(_personshare);
					_pt.setLat(_latitude);
					_pt.setLon(_longitude);
					_pt.setTime();
					if(databasePhongtro.updatephongtro(_pt))
					{
						for (int i = 0; i < listLocation.size(); i++) {
							if(listLocation.get(i).getId().equals(_pt.getId()))
							{
								listLocation.get(i).editPhongtro(_pt);
								Toast.makeText(getApplicationContext(), "Edit is success", Toast.LENGTH_LONG).show();
								break;
							}
						}
					}
					else
					{
						Toast.makeText(getApplicationContext(), "Edit is not success", Toast.LENGTH_LONG).show();
					}
					break;
				default:
					break;
				}
			}
			break;
		default:
				break;
		}
		Log.d("refesh ", "1");
		refeshEdit();
	}
    
  
	//-----------------------------------------------------------------------------------------------
    // function
    
	 public boolean isOnline() {
		 boolean status=false;
		    try{
		        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		        NetworkInfo netInfo = cm.getNetworkInfo(0);
		        if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
		            status= true;
		        }else {
		            netInfo = cm.getNetworkInfo(1);
		            if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
		                status= true;
		        }
		    }catch(Exception e){
		        e.printStackTrace();  
		        return false;
		    }
		    return status;

		}

    
    public void refeshEdit()
    {
    	Log.d("refesh", "2");
    	mymap.clear();
    	for (int i = 0; i < listLocation.size(); i++) {
    		Log.d("refesh", "3+i="+i);
    		markerNewPoint(listLocation.get(i));
    		Log.d("refesh", "4+i="+i);
		}
    }
    
    public void markerNewPoint(phongtro pt)
    {
    	LatLng point = new LatLng(pt.getLat(), pt.getLon());
    	String tt = "";
    	tt+=pt.getAddress();
    	if(pt.getPrice()<=-1.0)
    	{
    		tt+="\n agreement";
    	}
    	else
    	{
    		tt+="\n "+ pt.getPrice();
    	}
    	tt+="\n "+pt.getContact(); 
    	
    	if(pt.getPersonShare())
    	{
    		Time td= new Time();
    		td.setToNow();
    		
    		if(td.year==pt.getYear())
    		{
    			if(td.month==pt.getMonth())
    			{
    				if(td.monthDay-pt.getDay()<=7)
    				{
    					mymap.addMarker(new MarkerOptions().
    			      			icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).
    			      			position(point).title(tt));
    				
    				}
    				else
    				{
    					mymap.addMarker(new MarkerOptions().
			        			icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).
			        			position(point).title(tt));
    				}
    			}
    			else
    			{
    				if(td.month-pt.getMonth()<=1)
    				{
    					int x= td.monthDay+30-pt.getDay();
    					if(x<=7)
    					{
    						mymap.addMarker(new MarkerOptions().
        			      			icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).
        			      			position(point).title(tt));
        				
        				}
        				else
        				{
        					mymap.addMarker(new MarkerOptions().
    			        			icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).
    			        			position(point).title(tt));
        				}
    				}
    				else
    				{
    					mymap.addMarker(new MarkerOptions().
			        			icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).
			        			position(point).title(tt));
    				}
    			}
    		}
    		else//different year
    		{
    			if(td.month!=1)
    			{
    				mymap.addMarker(new MarkerOptions().
		        			icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).
		        			position(point).title(tt));
    			}
    			else if(pt.getMonth()!=12)
    			{
    				mymap.addMarker(new MarkerOptions().
		        			icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).
		        			position(point).title(tt));
    			}
    			else
    			{
    				int x= td.monthDay+30-pt.getDay();
					if(x<=7)
					{
						mymap.addMarker(new MarkerOptions().
    			      			icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).
    			      			position(point).title(tt));
    				
    				}
    				else
    				{
    					mymap.addMarker(new MarkerOptions().
			        			icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).
			        			position(point).title(tt));
    				}
    			}
    		}
    		
    	}
    	else//not share
    	{
    		mymap.addMarker(new MarkerOptions().
        			icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)).
        			position(point).title(tt));
    	}
    } 
    
    public Boolean checkSelect() {
    	for (int i = 0; i < adtPT.getCount(); i++) {
			View pt = lsvShow.getChildAt(i);
			CheckBox chk = (CheckBox)pt.findViewById(R.id.checkBox_adt_check);
			if(!chk.isChecked())
			{
				return false;
			}
		}
		return true;
	}
    




	
	/* __________________________________________________________________ */
	/* ============== Các hàm dùng để vẽ đường đi ==================== */
	private String getDirectionsUrl(LatLng origin, LatLng dest) {

		// Origin of route
		String str_origin = "origin=" + origin.latitude + ","
				+ origin.longitude;
		// Destination of route
		String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
		// Sensor enabled
		String sensor = "sensor=false";
		// Building the parameters to the web service
		String parameters = str_origin + "&" + str_dest + "&" + sensor;
		// Output format
		String output = "json";
		// Building the url to the web service
		String url = "https://maps.googleapis.com/maps/api/directions/"
				+ output + "?" + parameters;
		return url;
	}

	/** A method to download json data from url */
	private String downloadUrl(String strUrl) throws IOException {
		String data = "";
		InputStream iStream = null;
		HttpURLConnection urlConnection = null;
		try {
			URL url = new URL(strUrl);

			// Creating an http connection to communicate with url
			urlConnection = (HttpURLConnection) url.openConnection();

			// Connecting to url
			urlConnection.connect();

			// Reading data from url
			iStream = urlConnection.getInputStream();

			BufferedReader br = new BufferedReader(new InputStreamReader(
					iStream));

			StringBuffer sb = new StringBuffer();

			String line = "";
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}

			data = sb.toString();

			br.close();

		} catch (Exception e) {
			Log.d("Exception while downloading url", e.toString());
		} finally {
			iStream.close();
			urlConnection.disconnect();
		}
		return data;
	}
	
		
		private class DownloadTask extends AsyncTask<Void, Void, PolylineOptions> {
			
			
			String data = "";
			// Downloading data in non-ui thread
			@Override
			protected PolylineOptions doInBackground(Void... url) {
				Log.d("get the way", "begin download url");
						// Getting URL to the Google Directions API
						String urls = getDirectionsUrl(locationOrigin, locationDest);
						Log.d("get the way", "make direction url");
						try {
							// Fetching the data from web service
							data = downloadUrl(urls);
							Log.d("get the way", "load is ok");
						} catch (Exception e) {
							Log.d("Background Task", e.toString());
						}

						/** */
						Log.d("get the way", "make JSON Oject");
						JSONObject jObject;
						List<List<HashMap<String, String>>> routes = null;
						Log.d("get the way", "make JSON Oject 1");
						try {
							jObject = new JSONObject(data);
							DirectionsJSONParser parser = new DirectionsJSONParser();
							Log.d("get the way", "make JSON Oject 2");
							// Starts parsing data
							routes = parser.parse(jObject);
						} catch (Exception e) {
							e.printStackTrace();
						}
						Log.d("get the way", "make JSON Oject 3");
						/** Lấy danh sách và phân tích ra. */
						ArrayList<LatLng> points = null;
						PolylineOptions lineOptions = null;
						Log.d("get the way", "create polyline option");
						// MarkerOptions markerOptions = new MarkerOptions();
						String distance = "";
						String duration = "";

						if (routes.size() < 1) {
//							Toast.makeText(getBaseContext(), "No Points",
//									Toast.LENGTH_SHORT).show();
							return null;
						}

						// Traversing through all the routes
						for (int i = 0; i < routes.size(); i++) {
							points = new ArrayList<LatLng>();
							lineOptions = new PolylineOptions();

							// Fetching i-th route
							List<HashMap<String, String>> path = routes.get(i);

							// Fetching all the points in i-th route
							for (int j = 0; j < path.size(); j++) {
								HashMap<String, String> point = path.get(j);

								if (j == 0) { // Get distance from the list
									distance = point.get("distance");
									continue;
								} else if (j == 1) { // Get duration from the list
									duration = point.get("duration");
									continue;
								}

								double lats = Double.parseDouble(point.get("lat"));
								double lngs = Double.parseDouble(point.get("lng"));
								LatLng position = new LatLng(lats, lngs);

								points.add(position);
							}

							// Adding all the points in the route to LineOptions
							
							lineOptions.addAll(points);
							lineOptions.width(5);
							lineOptions.color(Color.GREEN);// set color for way

						}
				return lineOptions;

			}

			// Executes in UI thread, after the execution of
			// doInBackground()
			@Override
			protected void onPostExecute(PolylineOptions result) {
				super.onPostExecute(result);
				/* Add marker và vẽ đường đi. */
				//addMarker(Place_._atm);
				Log.d("get the way", "excute");
				mymap.addPolyline(result);
				Log.d("get the way", "that all");
				dismissDialog(0);
			}
		}
}